import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PraseMain {
    public static void DoParse() {
        // 初始化文法规则
        LexicalMain.DoLex();
        ArrayList<Formula> formulas = new ArrayList<>();
        Set<String> nonTerminals1 = new HashSet<>();
        Set<String> terminals1 = new HashSet<>();
        try {
            String content = readFileContent(Config.expand);
            processGrammarContent(content, formulas, nonTerminals1, terminals1);
        } catch (Exception e) {
            e.getStackTrace();
        }

        ArrayList<String> nonTerminals = new ArrayList<>(nonTerminals1);
        ArrayList<String> terminals = new ArrayList<>(terminals1);

        // 创建一个存储 First 集合的 HashMap
        HashMap<String, ArrayList<String>> firsts = new HashMap<>();

        // 创建 FirstSet 对象并计算 First 集合
        FirstSet firstSet = new FirstSet();
        firstSet.setFirst(formulas, terminals, nonTerminals, firsts);

        // 输出每个符号的 First 集合
        // for (String symbol : nonTerminals) {
        // System.out.println("First(" + symbol + ") = " + firsts.get(symbol));
        // }
        // 初始化 Follow 集合（将会被填充）
        HashMap<String, ArrayList<String>> follows = new HashMap<>();

        // 创建 FollowSet 对象并计算 Follow 集合
        FollowSet followSet = new FollowSet();
        followSet.setFollow(firstSet.formulas, firstSet.terminals, firstSet.nonTerminals, firstSet.firsts, follows);

        // 输出结果
        // System.out.println("Follow sets:");
        // for (String nonTerminal : nonTerminals) {
        // System.out.println(nonTerminal + " -> " + follows.get(nonTerminal));
        // }
        //
        HashMap<String, Formula> predictMap = new HashMap<>();
        PredictMap.setPredictionMap(formulas, terminals, nonTerminals, firsts, follows, predictMap);

        // 输出预测表
        System.out.println("PredictMap:");
        for (String nonTerminal : nonTerminals) {
            for (String terminal : terminals) {
                String predictMapKey = PredictMap.getMapKey(terminal, nonTerminal);
                if (predictMap.get(predictMapKey) != null) {
                    System.out.print("终结符:" + terminal + " " + "文法:" + nonTerminal + " -> ");
                    for (String s : predictMap.get(predictMapKey).getRight()) {
                        System.out.print(s);
                    }
                    System.out.println();
                }
            }

        }
        GrammarParse.grammar_parse_result = new ArrayList<>();
        GrammarParse.symbol_stack = new ArrayList<>();
        GrammarParse.input_str = LexicalMain.getLex_result_stack();
        System.out.println(LexicalMain.getLex_result_stack());
        GrammarParse.predictMap = predictMap;
        GrammarParse.Parse();
        GrammarParse.printParseResult();
        try {
            // BufferedWriter out = new BufferedWriter(new
            // FileWriter(Config.firstTablePath));
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(Config.firstTablePath), "UTF-8"));
            for (String s : firsts.keySet()) {
                out.write(s + "\t" + firsts.get(s) + "\n");
            }
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            // BufferedWriter out = new BufferedWriter(new
            // FileWriter(Config.followTablePath));
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(Config.followTablePath), "UTF-8"));
            for (String s : follows.keySet()) {
                out.write(s + "\t" + follows.get(s) + "\n");
            }
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            // BufferedWriter out = new BufferedWriter(new
            // FileWriter(Config.predictMapPath));
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(Config.predictMapPath), "UTF-8"));
            for (String s : predictMap.keySet()) {
                out.write(s + "\t" + "formula: " + predictMap.get(s).getLeft() + "->" +
                        Arrays.toString(predictMap.get(s).getRight()) + "\n");
            }
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 读取文件内容
    private static String readFileContent(String filename) throws IOException {
        StringBuilder content = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(filename), StandardCharsets.UTF_8)) {
            char[] buffer = new char[1024];
            int len;
            while ((len = reader.read(buffer)) != -1) {
                content.append(buffer, 0, len);
            }
        }
        return content.toString();
    }

    // 按行分割内容
    private static String[] splitContentToLines(String content) {
        return content.split("\\r?\\n");
    }

    // 按空格分割内容
    private static String[] splitContentToWords(String content) {
        return content.split("\\s+");
    }

    private static void processGrammarContent(String content, List<Formula> formulas, Set<String> nonTerminalsSet,
            Set<String> terminalsSet) {
        String[] chapters = splitContentToLines(content);

        // 遍历文法内容生成规则和非终结符集合
        for (String chapter : chapters) {
            String[] parts = splitContentToWords(chapter);
            if (parts.length > 2) {
                String nonTerminal = parts[0];
                String[] rightSide = Arrays.copyOfRange(parts, 2, parts.length);

                formulas.add(new Formula(nonTerminal, rightSide));
                nonTerminalsSet.add(nonTerminal);
            }
        }

        // 识别终结符集合
        for (String chapter : chapters) {
            String[] parts = splitContentToWords(chapter);
            for (int i = 2; i < parts.length; i++) {
                if (!nonTerminalsSet.contains(parts[i])) {
                    terminalsSet.add(parts[i]);
                }
            }
        }
    }
}
